package Hxw3DEngine.core.component.sound 
{
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.utils.ByteArray;
	import Hxw3DEngine.core.component.Component3D;
	import Hxw3DEngine.core.component.ComponentType;
	import Hxw3DEngine.asset.*;
	
	
	/**
	 * ...
	 * @author ...
	 */
	public class Sound3D extends Component3D 
	{
		
		public function Sound3D(_url:String = "",_isFadein:Boolean = true,_isFadeOut:Boolean = true,_isLoop:Boolean = true) 
		{
			super();
			_type = ComponentType.dynamicComponent;
			
			url = _url;
			isFadein = _isFadein;
			isFadeOut = _isFadeOut;
			isLoop = _isLoop;
		}
		
		
		private var _url:String;
		
		public function set url(value:String):void{
			if(value != ""){
				_url = value;
				initSound();
			}
		}
		
		public function get url():String{
			return _url;
		}
		
		public var isFadein:Boolean;
		
		public var isFadeOut:Boolean;
		
		public var isLoop:Boolean;
		
		private var sound:Sound;
		
		private var channal:SoundChannel;
		
		private var soundData:ByteArray;
		
		//当前是否在播放
		private var isPlaying:Boolean = false;
		
		
		//是否准备好播放
		private var isReady:Boolean = false;
		
		//是否加载完成就播放
		private var isPlay:Boolean = false;
		
		private function initSound():void {
			soundData = AssetManage.getAsset(url);
			if(!soundData){
				AssetManage.load(url,onComplete);
			}else{
				onComplete();
			}
		}
		
		private function onComplete():void{
			soundData = AssetManage.getAsset(url);
			sound = new Sound();
			sound.loadCompressedDataFromByteArray(soundData,soundData.bytesAvailable);
			isReady = true;
			if(isPlay && !isPlaying) playSound();
		}
		
		//播放音乐  也可以在播放进行时换成其它音乐
		public function play(_url:String = ""):void{
			if(_url != ""){
				if(isPlay) sound.close();
				isPlay = true; isReady = false;
				url = _url;
				initSound();
				return ;
			}
			
			//如果该音乐数据立即准备好立即播放
			if(isReady && !isPlaying){
				playSound();
			}else{//加载完成立即播放
				isPlay = true;
			}
		}
		
		private function playSound():void{
			//检查声音通道之前是不是用过，用过就清掉
			if(channal){
				channal.removeEventListener(Event.SOUND_COMPLETE,onPlayComplete);
				channal = null;
			}
			isPlaying = true;
			channal = sound.play();
			channal.addEventListener(Event.SOUND_COMPLETE,onPlayComplete);
		}
		
		
		//播放完成销毁自身
		private function onPlayComplete(e:Event):void{
			isPlaying = false;
			if(isLoop){
				play();
			}else{
				destry();
			}
		}
		
		private function destry():void{
			sound = null;
			soundData = null;
			channal = null;
		}
		
		
		
		
	}

}